﻿
using Models;
using System;
using System.Linq;
using System.Web;
using WxPayAPI;
using System.Text.RegularExpressions;
using Common.Model;
/// <summary>
/// UserBase 的摘要说明
/// </summary>
public class UserBase : System.Web.UI.Page
{

    protected string appId = WxPayConfig.APPID;
    protected string signature;

    public Wechat_Sdk wechat_Sdk;
    public int sum, userOneSum, querySubSum, gapSum;
    public string guid;

    Entities db = new Entities();
    public UserBase()
    {
        //
        // TODO: 在此处添加构造函数逻辑
        //
        this.Load += new EventHandler(UserBase_Load);
    }

    void UserBase_Load(object sender, EventArgs e)
    {
        //清除浏览器缓存
        Response.Buffer = true;
        Response.ExpiresAbsolute = DateTime.Now.AddDays(-1);
        Response.Cache.SetExpires(DateTime.Now.AddDays(-1));
        Response.Expires = 0;
        Response.CacheControl = "no-cache";
        Response.Cache.SetNoStore();

        //到wxProces中取OpenId，取到后再跳回当前页面
        if (Session["SOPENID"] == null || Session["SOPENID"].ToString() == string.Empty || Session["UGUID"] == null || Session["UGUID"].ToString() == string.Empty)
        {
            //  到wxProces中取OpenId，取到后再跳回当前页面
            //传递上级会员参数
            if (Request.QueryString["pid"] != null && Request.QueryString["pid"] != "")
            {
                string pid = Request.QueryString["pid"].ToString();

                Utils.WriteCookie("pid", "lncms", pid);
            }
            //else
            //{
            //    Utils.WriteCookie("pid", "lncms", 0);
            //}

           

            Response.Redirect("/4g/login/wxProcess.aspx?reurl=" + HttpUtility.UrlEncode(Request.RawUrl));
            Response.End();
            //if (Session["GUID"] == null || Session["GUID"].ToString() == String.Empty)
            //{      
            //    Response.Redirect("/4g/login/login.aspx?reurl=" + HttpUtility.UrlEncode(Request.RawUrl));
            //    Response.End();
            //}
        }
        else
        {
            string OPENID = Session["SOPENID"].ToString();
            var wxuser = db.User.SingleOrDefault(p => p.UOpenID == OPENID);
            if (string.IsNullOrEmpty(wxuser.UIndirectParentId) || string.IsNullOrEmpty(wxuser.UTel))   //没有上级，也没有认证电话
            {
                Response.Redirect("/4g/login/reg.aspx");
            }

        }

    }

    /// <summary>
    /// 检查登录微信用户
    /// </summary>
    /// <param name="wiopid"></param>
    /// <returns></returns>
    public bool ULogin(string wxopid)
    {
        using (Entities db = new Entities())
        {
            var NUId = Convert.ToInt32(db.WXUserInfo.SingleOrDefault(p => p.SOpenId == wxopid).NUId);
            if (NUId == 0)
            {
                return false;
            }
            else
            {
                var mydd = db.User.SingleOrDefault(p => p.UID == NUId);
                if (mydd == null)
                {
                    return false;
                }
                else
                {

                    Session["UID"] = mydd.UID;
                    Session["GUID"] = mydd.UGuid;
                    Session["HUTYPE"] = mydd.Ustate;

                    //设置超时时间
                    Session.Timeout = 45;
                    Session["AdminLoginSun"] = null;
                    return true;

                }

            }

        }


    }


    /// <summary>
    /// 检查登录用户
    /// </summary>
    /// <param name="UserName"></param>
    /// <param name="UserPwd"></param>
    /// <returns></returns>
    public bool ULogin(string UserName, string UserPwd)
    {
        using (Entities db = new Entities())
        {

            var mydd = db.User.SingleOrDefault(p => p.UTel == UserName);
            if (mydd == null)
            {

                User Lt = new User();
        
                    Lt.UTel = UserName;
                    Lt.Umima = DESEncrypt.Encrypt(UserPwd.Trim());
                    Lt.UGuid =GenerateStringID();
                    Lt.Ustate=1;
                    db.User.Add(Lt);
                    db.SaveChanges();

                Session["UID"] = Lt.UID;
                Session["GUID"] = Lt.UGuid;
                Session["HUTYPE"] = Lt.Ustate;
                return true;

            }
            else
            {
                string Md5_userpassword = DESEncrypt.Encrypt(UserPwd.Trim());
                //判断密码的正确性
                if (Md5_userpassword != mydd.Umima)
                {
                    //HttpContext.Current.Response.Write("<script>alert('用户密码错误，请确认你的身份!!!');</script>");
                    return false;
                }
                else
                {
                    Session["UID"] = mydd.UID;
                    Session["GUID"] = mydd.UGuid;
                    Session["HUTYPE"] = mydd.Ustate;

                    //设置超时时间
                    Session.Timeout = 45;
                    Session["AdminLoginSun"] = null;
                    //写入Cookies
                    //Utils.WriteCookie("AdminName", "lncms", DESEncrypt.Encrypt(mydd.Uname));
                    // Utils.WriteCookie("AdminPwd", "lncms", mydd.Umima);
                    return true;

                }

            }
        }


    }
    //下面的方法会生成一个短的字符串，并且这个字符串是唯一的。重复1亿次都不会出现重复的，它也是依照GUID的唯一性来生成这个字符串的。
    private string GenerateStringID()
    {
        long i = 1;
        foreach (byte b in Guid.NewGuid().ToByteArray())
        {
            i *= ((int)b + 1);
        }
        return string.Format("{0:x}", i - DateTime.Now.Ticks);
    }

    /// <summary>
    /// 日志写入
    /// </summary>
    /// <param name="str"></param>
    public void SaveLogs(string username, string str)
    {

        Entities mydb = new Entities();
        {
            L_Log Lg = new L_Log();

            Lg.L_TiTLE = str;
            Lg.L_Time = DateTime.Now;
            Lg.L_IP = GetIP();
            Lg.L_UID = username;
            mydb.L_Log.Add(Lg);
            mydb.SaveChanges();

        }
    }


    public void SaveErrorLogs(string title)
    {

    
        Entities mydb = new Entities();
        {
            L_Log Lg = new L_Log();

            Lg.L_TiTLE = title;
            Lg.L_Time = DateTime.Now;
            Lg.L_IP = GetIP();
            Lg.L_UID = "0";
            mydb.L_Log.Add(Lg);
            mydb.SaveChanges();

        }
    }

    public static string GetIP()
    {
        string result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

        if (string.IsNullOrEmpty(result))
            result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

        if (string.IsNullOrEmpty(result))
            result = HttpContext.Current.Request.UserHostAddress;

        if (string.IsNullOrEmpty(result) || !IsIP(result))
            return "127.0.0.1";

        return result;
    }

    #region 检查是否为IP地址
    /// <summary>
    /// 是否为ip
    /// </summary>
    /// <param name="ip"></param>
    /// <returns></returns>
    public static bool IsIP(string ip)
    {
        return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
    }
    #endregion


}